﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using System.Windows;
using System.Windows.Media.Imaging;
using eLearning.Model;
using eLearning.Util;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Tasks;
using Newtonsoft.Json;

namespace eLearning.View
{
    public partial class PengumumanFormPage : PhoneApplicationPage
    {
        private bool firstLoaded;
        private Pengumuman pengumuman;
        
        public PengumumanFormPage()
        {
            InitializeComponent();

            this.Loaded += new RoutedEventHandler(RssItemPage_Loaded);
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            if (e.NavigationMode == System.Windows.Navigation.NavigationMode.Back)
                firstLoaded = false;
            else
                firstLoaded = true;
        }

        #region Event Handlers
        private void RssItemPage_Loaded(object sender, RoutedEventArgs e)
        {
            pengumuman = (Pengumuman)DataContext;
            if (firstLoaded)
            {
                if (pengumuman != null)
                {
                    if (pengumuman != null && pengumuman.Id != null)
                    {
                        textBoxPerihal.Text = pengumuman.Perihal;
                        textBoxPengumuman.Text = pengumuman.Info;
                        uploadLink = pengumuman.ImageUrl;
                        imagePengumuman.Source = string.IsNullOrEmpty(uploadLink) ? null : new BitmapImage(new Uri(uploadLink));
                        if ("1".Equals(pengumuman.Status))
                            checkActive.IsChecked = true;
                        else
                            checkNonActive.IsChecked = false;
                    }
                    else
                    {
                        textBoxPerihal.Text = "";
                        textBoxPengumuman.Text = "";
                    }
                }                
            }
        }

        #endregion

        private void CreateAnnouncement(object data)
        {
            string json = null, url = null;

            if (data is Pengumuman)
            {
                Pengumuman pengumuman = (Pengumuman)data;
                if (pengumuman.Id == null)
                {
                    pengumuman.Creator = (Dosen)SavedUser.Instance.User.ConvertUser();
                    url = Config.Instance.ANNOUNCE_SERVICE_URL() + Config.ADD_ACTION_KEY; //create
                }
                else
                {
                    url = Config.Instance.ANNOUNCE_SERVICE_URL() + Config.UPDATE_ACTION_KEY; //update
                }
                json = JsonConvert.SerializeObject(pengumuman);
            }
            
            Uri uri = new Uri(url, UriKind.Absolute);
            WebClient client = new WebClient();

            client.Encoding = Encoding.UTF8;
            client.Headers[HttpRequestHeader.ContentType] = "application/json";
            client.Headers[HttpRequestHeader.ContentLength] = json.Length.ToString();

            client.UploadStringCompleted += new UploadStringCompletedEventHandler(createAnnouncement_UploadStringCompleted);

            try
            {
                client.UploadStringAsync(uri, "POST", json);
            }
            catch (Exception) { }
        }

        private void createAnnouncement_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
        {
            try
            {
                if (e.Cancelled || e.Error != null)                
                    return;
                
                MessageBox.Show("Message : " + e.Result);

                if (e.Result.Contains("Success"))
                    NavigationService.GoBack();

            }
            catch (Exception ex)
            {
                MessageBox.Show("ERROR : " + ex.Message);
            }
        }

        private void buttonSave_Click(object sender, System.EventArgs e)
        {
            if (pengumuman != null)
            {
                pengumuman.Perihal = textBoxPerihal.Text;
                pengumuman.Info = textBoxPengumuman.Text;
                pengumuman.ImageUrl = uploadLink;
                pengumuman.Status = checkActive.IsChecked == true ? "1" : "0";
                CreateAnnouncement(pengumuman);
            }            
        }

        private void buttonCancel_Click(object sender, System.EventArgs e)
        {
            NavigationService.GoBack();
        }

        private void buttonUpload_Click(object sender, RoutedEventArgs e)
        {
            PhotoChooserTask objPhotoChooser = new PhotoChooserTask();
            objPhotoChooser.Completed += new EventHandler<PhotoResult>(PhotoChooseCall);
            objPhotoChooser.Show();
        }

        private void PhotoChooseCall(object sender, PhotoResult e)
        {
            switch (e.TaskResult)
            {
                case TaskResult.OK:                    
                    Dictionary<string[], object> data = new Dictionary<string[], object>()
                    {
                        {new string[]{"uploadedfile", e.OriginalFileName}, FileUtil.ReadToEnd(e.ChosenPhoto)}
                    };

                    parameters = data;
                    UploadFile(Config.Instance.UPLOAD_SERVICE_URL() + Config.UPLOAD_ANNOUNCE_KEY);

                    break;
                case TaskResult.Cancel:
                    MessageBox.Show("Cancelled");
                    break;
                case TaskResult.None:
                    MessageBox.Show("Nothing Entered");
                    break;
            }
        }


        string uploadLink = "";
        string boundary = "----------" + DateTime.Now.Ticks.ToString();
        public Dictionary<string[], object> parameters;

        public void UploadFile(string url)
        {
            HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(new Uri(url));
            myRequest.Method = "POST";
            myRequest.ContentType = string.Format("multipart/form-data; boundary={0}", boundary);

            myRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), myRequest);
        }

        private void GetRequestStreamCallback(IAsyncResult asynchronousResult)
        {
            HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
            Stream postStream = request.EndGetRequestStream(asynchronousResult);

            FileUtil.writeMultipartObject(postStream, parameters, boundary);
            postStream.Close();

            request.BeginGetResponse(new AsyncCallback(GetResponseCallback), request);
        }

        private void GetResponseCallback(IAsyncResult asynchronousResult)
        {
            HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
            HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);

            Stream streamResponse = response.GetResponseStream();
            StreamReader streamRead = new StreamReader(streamResponse, Encoding.UTF8);

            uploadLink = streamRead.ReadToEnd();

            this.Dispatcher.BeginInvoke(() =>
            {
                imagePengumuman.Source = new BitmapImage(new Uri(uploadLink));
            });
            streamResponse.Close();
            response.Close();
        }     
   
    }
}